/* https://gitlab.com/void-hikari/void-fm */

var historylist = [];

$(document).ready(function() {
    var player = $("#player");
    var next = $("#player-wrapper #next");
    var name = $("#player-wrapper #name");
    var img = $("body");
    var repeat = $(".jp-repeat");
    var title = $("title").html();
    var counts = 0;

    //是否是已播放的id
    function isHistoryID(id) {
        if(historylist.length == counts){
            historylist = [];
        }
        for (var i = historylist.length - 1; i >= 0; i--) {
            if (id == historylist[i]) {
                return true;
            }
        }
        return false;
    }

    //取随机不重复id
    function randomID() {
        var id = Math.ceil(Math.random() * counts);
        if (isHistoryID(id)) {
            return randomID();
        }
        else{
            return id;
        }
    }

    //获取信息并播放音乐
    function playMusic(id) {
        $.ajax({
            url: window.location.protocol + "//" + window.location.host + "/index.php/fm/get/" + id,
            type: "GET",
            dataType: "json",
            success: function (data) {
                if(data.id !== null) {
                    var stream = {
                        mp3: data.url
                    };
                    data.img = "url(" + data.img + ")";
                    img.css("background-image",data.img);
                    name.text(data.name);
                    window.location.href = window.location.protocol + "//" + window.location.host + "#!" + data.id;
                    $("title").html(data.name + " - " + title);
                    player.jPlayer("setMedia", stream).jPlayer("play");
                    if (!isHistoryID(data.id)) {
                        historylist.push(data.id);
                    }
                }
                else {
                    playMusic(randomID());
                }
            }
        });
    }

    //获取最大id并初始音乐
    $.ajax({
        url: window.location.protocol + "//" + window.location.host + "/index.php/fm/counts",
        type: "GET",
        dataType: "json",
        success: function (data) {
            counts = data.counts;

            //因为异步请求，等这个请求返回后再初始音乐
            if(window.location.hash) {
                playMusic(window.location.hash.replace(/#!/,""));
            }
            else {
                playMusic(randomID());
            }
        }
    });

    //播放完毕切歌
    player.jPlayer({
        ended: function(event) {
            if (repeat.css('display') == 'none') {
                player.jPlayer("play");
			}else {
                playMusic(randomID());
            }
        },
        supplied: "mp3",
        volume: 1,
        cssSelectorAncestor: "#player-wrapper",
    });

    //下一个
    next.click(function() {
        player.jPlayer("pause");
        name.text("加载中...");
        playMusic(randomID());
    });

    console.log("https://gitlab.com/void-hikari/void-fm");
});